import React, { useEffect, useState, useRef } from 'react'
import { NavigationStackScreenComponent } from 'react-navigation-stack'
import { ScrollView, View, Text, TouchableOpacity, SectionList, Alert, Image } from 'react-native';
import { commonStyle, translateSize, definedColors } from 'styles';
import { ShortBar, InfoLayout, InputMoney, ChangeCard, SettingMoney, RadiusButton, Toast } from 'components';
import { recognitionConfirmStyle } from './styles'
import pos, { PosAppMdmFqOutput, PosAppCustomer, PosAppBank, PosAppBankIuput, PosGetInCustomer } from 'api/pos'
import { getAuthorization, operate } from 'services/authorization'
import ChooseRoom, { RoomInfo } from './components/choose-room/ChooseRoom'
import PayButton from './components/PayButton';
import Loading from 'components/loading';
import { PosAppZskOption, Custom } from '../../api/pos';
import ModalDropdown from 'react-native-modal-dropdown';
import assets from 'modules/assets';
import { dropdownIcon, dropdownRow } from './components/choose-room/style';
import { navigate } from 'services/navigation';
import ChooseCustomer from './components/choose-customer/ChooseCustomer';
import TreeSelect, { TreeItem } from 'react-native-tree-select';
import QccTreeSelect from './components/qcc-tree-select/QccTreeSelect';
/**
 * 收暂收款
 * @param props
 */
const AdvanceFundScreen: NavigationStackScreenComponent<{
	customerInfo: PosAppCustomer
	onChoose: () => void
	bankList: PosAppBank[]
	fundName: string
	zskOptionList: PosAppZskOption[]
}> = props => {

	const [customerInfo, setCustomerInfo] = useState<PosAppCustomer>({})
	const [showChoose, setShowChoose] = useState(false);
	const [showChooseCustomer, setShowChooseCustomer] = useState(false);
	const [showChooseFund, setShowChooseFund] = useState(false);
	const [roomData, setRoomData] = useState<PosAppMdmFqOutput[]>([]);
	const [currentRoomInfo, setCurrentRoomInfo] = useState<RoomInfo>({})
	const [bank, setBank] = useState<PosAppBank>({})
	const [bankList, setBankList] = useState<PosAppBank[]>([])
	const [money, setMoney] = useState(0.00)
	const [fund, setFund] = useState<PosAppZskOption>({})
	const [zskOptionList, setZskOptionList] = useState<PosAppZskOption[]>([]);
	const [zskTreeOptionList, setTreeZskOptionList] = useState<TreeItem[]>([]);
	const [posGetInCustomerList, setPosGetInCustomerList] = useState<PosGetInCustomer[]>([])
	const dropdownRef = useRef<ModalDropdown>();

	useEffect(() => {
		Loading.show()
		let customerInfo = props.navigation.getParam('customerInfo')
		setCustomerInfo(customerInfo || {})
		setPosGetInCustomerList([{ erpCustomerId: customerInfo.erpId, customerName: customerInfo.name, zjType: customerInfo.zjType, zjNumber: customerInfo.zjNumber, tel: customerInfo.tel }])
		let zskOptionDataList = props.navigation.getParam('zskOptionList')
		setZskOptionList(zskOptionDataList || [])
		toTreeData(zskOptionDataList || [])
		setFund(zskOptionDataList && zskOptionDataList.length > 0 && zskOptionDataList.find(d => d.type === 1) || { name: '暂收款', id: 11 })
		// let bankList = props.navigation.getParam('bankList')
		// bankList.length > 0 && setBank(bankList[0])
		console.log('333', zskOptionDataList && zskOptionDataList.length > 0 && zskOptionDataList.find(d => d.type === 1) || { name: '暂收款', id: 11 })
		pos.posApp.getFqList({ id: getAuthorization().project.id }).then(res => {
			setRoomData(res)
		}).finally(() => {
			Loading.hide()
		})
		props.navigation.setParams({
			onChoose: () => {
				setShowChoose(true)
			}
		});

	}, [])


	useEffect(() => {
		loadBank()
	}, [currentRoomInfo.roomId, fund.id, getAuthorization().project.id])

	const toTreeData = (data: PosAppZskOption[]) => {
		let cache = new Map<string, TreeItem>()
		let zskTreeData = data.map((item: PosAppZskOption) => {
			return { id: item.id.toString(), name: item.fundName, sortNo: item.fullCode, parentId: item.parentId.toString() } as TreeItem
		})
		let treeData = []
		for (let item of zskTreeData) {
			item.children = []
			let parentItem = cache.get(item.parentId.toString())
			if (parentItem) {
				parentItem.children.push(item)
			} else {
				treeData.push(item)
			}
			cache.set(item.id.toString(), item)
		}
		setTreeZskOptionList(treeData)
	}

	//暂收款根据房间和款项id获取入账银行
	const loadBank = () => {
		let posAppBankIuput = {} as PosAppBankIuput
		posAppBankIuput.roomCode = currentRoomInfo.roomId
		posAppBankIuput.fundId = fund.id
		posAppBankIuput.projectId = getAuthorization().project.id
		posAppBankIuput.mac = getAuthorization().mac
		posAppBankIuput.scene = 'szsk'
		pos.posApp.getBankByScene(posAppBankIuput).then(res => {
			setBankList(res || [])
			if (res && res.length === 1) {
				setBank(res[0])
			} else {
				setBank({})
			}
		})
	}

	const renderFundListTree = () => {
		// return <Dropdown data={unitData} defaultValue={currentUnit}
		// onSelect={(index: string, option: PosAppMdmDyOutput) => { setCurrentUnit(option) }} />
		<View></View>
	}

	const renderFundList = () => {
		// return <Dropdown data={unitData} defaultValue={currentUnit}
		// onSelect={(index: string, option: PosAppMdmDyOutput) => { setCurrentUnit(option) }} />
		return <ModalDropdown<PosAppZskOption>
			dropdownStyle={{ width: '30%' }}
			ref={ref => { dropdownRef.current = ref }}
			dropdownTextStyle={{ fontSize: translateSize(32) }}
			options={zskOptionList}
			renderRow={(option: PosAppZskOption, index: string, isSelected: boolean) => <Text style={dropdownRow}>{option.name}</Text>}
			onSelect={(index: string, option: PosAppZskOption) => {
				setFund(option)

			}}>
			<TouchableOpacity
				style={[commonStyle.containerRow]}
				onPress={() => { operate(); dropdownRef.current.show() }}>
				<Text style={{}}>{fund.name}</Text>
				<Image source={assets.images.icon_arrow_down} style={dropdownIcon} />
			</TouchableOpacity>
		</ModalDropdown>
	}

	return (
		<View style={{ height: '100%', width: '100%', position: 'relative' }}>
			<ScrollView>
				<View style={[commonStyle.containerColumn, recognitionConfirmStyle.container]}>
					<View style={{ ...commonStyle.containerRow, justifyContent: 'space-between' }}>
						<ShortBar style={{ ...recognitionConfirmStyle.userInfo, width: '50%' }} title="客户信息" />
						<TouchableOpacity
							style={commonStyle.headerRight}
							onPress={() => {
								operate()
								setShowChooseCustomer(true)
							}}>
							<Text style={{ ...commonStyle.tag, marginTop: translateSize(40), }}> 添加客户 </Text>
						</TouchableOpacity>
					</View>
					{
						posGetInCustomerList.map((posGetInCustomer: PosGetInCustomer, index: number) => {
							return <View key={posGetInCustomer.erpCustomerId} style={{ marginBottom: translateSize(10), position: 'relative' }}>
								{
									index !== 0 ? <TouchableOpacity
										style={{ position: 'absolute', left: translateSize(22), zIndex: 9999, borderColor: definedColors.firebrick, borderStyle: 'solid', top: translateSize(38), }}
										onPress={() => {
											operate()
											Alert.alert('确认', '确认删除该用户', [{
												text: "确认", onPress: () => {
													setPosGetInCustomerList(posGetInCustomerList.filter(c => c.erpCustomerId !== posGetInCustomer.erpCustomerId))
												}
											}, {
												text: "取消", onPress: () => {
													return true
												}
											}])
										}}>
										<Image source={assets.images.icon_close_yellow} style={{ width: translateSize(27), height: translateSize(27) }}></Image>
										{/* <Text style={{ color: definedColors.firebrick }}> X</Text> */}
									</TouchableOpacity> : null
								}

								{/* <Image source={assets.images.icon_close_yellow} style={{}}></Image> */}
								<InfoLayout title="客户名称:" content={posGetInCustomer.customerName} />
								<InfoLayout
									title="证件号码:"
									titlePartner={<Text style={commonStyle.tag}>{posGetInCustomer.zjType || '身份证'}</Text>}
									content={posGetInCustomer.zjNumber}
								/>
								<InfoLayout title="电话号码：" content={posGetInCustomer.tel} />
							</View>
						})
					}

					<View style={{ ...recognitionConfirmStyle.projectList, marginTop: translateSize(22), }}>
						<View style={[commonStyle.containerColumn, recognitionConfirmStyle.projectContainer]}>
							<ShortBar title={`${getAuthorization().project.name}-${currentRoomInfo.planName || ''}`} />
							<View style={[commonStyle.containerRow, recognitionConfirmStyle.projectInfoContainer]}>
								<Text style={{ ...recognitionConfirmStyle.projectInfo, ...commonStyle.roomStyle }}>{currentRoomInfo.roomName}</Text>
								{/* <Text style={commonStyle.tag}>收取POS机手续费</Text> */}
							</View>
						</View>

						<InfoLayout title="款项"
							content={fund.fundName}
							contentIcon={assets.images.icon_arrow_down}
							contentIconStyle={dropdownIcon}
							onContentPress={() => {
								setShowChooseFund(true)
							}} />
						<SettingMoney />
						<InputMoney editable={true} upperLimit={999999999} defaultValue={money} onChange={money => { setMoney(Number(money)) }} />
					</View>
					<ChangeCard bank={bank} bankList={bankList} onPress={(bank: PosAppBank) => { setBank(bank) }} />
					<PayButton onPress={(type: 'scan' | 'card') => {
						// pay(type)
					}} bank={bank} customer={customerInfo} posGetInCustomerList={posGetInCustomerList} feeList={[]} money={money} scene="szsk" refId={currentRoomInfo.roomId} fundId={fund.id} />
				</View>
			</ScrollView>
			<QccTreeSelect
				style={showChooseFund ? {} : { height: 0 }}
				treeData={zskTreeOptionList}
				onConfirm={(data) => { setFund(zskOptionList.find(zsk => zsk.id.toString() === data)); console.log('222', zskOptionList.find(zsk => zsk.id.toString() === data)); setShowChooseFund(false) }} onCancel={() => { setShowChooseFund(false) }} />
			<ChooseRoom
				style={showChoose ? {} : { height: 0 }}
				data={roomData}
				onConfirm={(data) => { setCurrentRoomInfo(data); setShowChoose(false) }} onCancel={() => { setShowChoose(false) }} />
			<ChooseCustomer key={Math.random()}
				style={showChooseCustomer ? {} : { height: 0 }}
				posGetInCustomerList={posGetInCustomerList}
				onConfirm={(data) => { setPosGetInCustomerList(data); setShowChooseCustomer(false) }} onCancel={() => { setShowChooseCustomer(false) }} />
		</View>
	)
}

AdvanceFundScreen.navigationOptions = props => {
	return {
		title: '收暂收款',
		headerRight: (
			<TouchableOpacity
				style={commonStyle.headerRight}
				onPress={() => {
					operate()
					let onChoose = props.navigation.getParam('onChoose');
					onChoose && onChoose();
				}}>
				<Text style={commonStyle.headerFont}>选择房间</Text>
			</TouchableOpacity>
		),
	}
}

export default AdvanceFundScreen
